package com.ikangtai.shecare.common;

import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;

import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.UpdateUtil;

import java.io.File;

public class DownloadService extends Service {
    private BroadcastReceiver receiver;

    public DownloadService() {}

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 如果Service在进程退出后有可能被系统自动重启，这个时候intent就会是null
        if(intent != null) {
            String downloadURL = intent.getStringExtra("downloadURL");

            receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    intent = new Intent(Intent.ACTION_VIEW);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setDataAndType(Uri.fromFile(new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/" + UpdateUtil.DOWNLOAD_APK_NAME)),
                            "application/vnd.android.package-archive");
                    startActivity(intent);
                    stopSelf();
                }
            };

            registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

            UpdateUtil updateUtil = new UpdateUtil(this);
            updateUtil.startDownload(downloadURL);

            return Service.START_STICKY;
        }else
            return super.onStartCommand(intent, Service.START_REDELIVER_INTENT, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}
